package com.example.readwrite;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class MyCache {

	private volatile Map<String, Object> map = new HashMap<String, Object>();

	private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
	private Lock readLock = readWriteLock.readLock();
	private Lock writeLock = readWriteLock.writeLock();

	public void put(String key, Object value) {
		readLock.lock();
		System.out.println(Thread.currentThread().getName() + " 正在写操作 " + key);
		try {
			TimeUnit.MICROSECONDS.sleep(300);

			map.put(key, value);
			System.out.println(Thread.currentThread().getName() + " 写完了 " + key);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			readLock.unlock();
		}

	}

	public Object get(String key) {
		writeLock.lock();
		Object result = null;
		System.out.println(Thread.currentThread().getName() + " 正在读操作 " + key);
		try {
			TimeUnit.MICROSECONDS.sleep(300);

			result = map.get(key);
			System.out.println(Thread.currentThread().getName() + " 取完了 " + key);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			writeLock.unlock();
		}

		return result;
	}
}

public class ReadWriteLockDemo {
	public static void main(String[] args) {
		MyCache myCache = new MyCache();

		// write
		for (int i = 1; i <= 5; i++) {
			final int num = i;
			new Thread(() -> {
				myCache.put(num + "", num + "");
			}, String.valueOf(i)).start();
		}

		// read
		for (int i = 1; i <= 5; i++) {
			final int num = i;
			new Thread(() -> {
				myCache.get(num + "");
			}, String.valueOf(i)).start();
		}
	}
}
